<template>
  <div class="app-container">
    <!-- 状态筛选按钮 -->
    <div class="status-filter mb-4">
      <el-button 
        :type="queryParams.status === 1 ? 'primary' : 'default'" 
        @click="filterByStatus(1)"
        class="mr-2"
      >
        正常开启的商户({{ enabledCount }})
      </el-button>
      <el-button 
        :type="queryParams.status === 0 ? 'primary' : 'default'" 
        @click="filterByStatus(0)"
      >
        已关闭商户({{ disabledCount }})
      </el-button>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入商户编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商户类型" clearable  style="width: 249px;">
          <el-option v-for="(label, value) in typeMap" :key="value" :label="label" :value="parseInt(value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName" label-width="100px">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入联系邮箱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['core:storeInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['core:storeInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['core:storeInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['core:storeInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商户ID" align="center" prop="id" />
      <el-table-column label="商户名称" align="center" prop="name" />
      <el-table-column label="商户编码" align="center" prop="code" />
      <el-table-column label="商户类型" align="center" prop="type">
        <template #default="scope">
          {{ typeMap[scope.row.type] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="商户LOGO图片地址" align="center" prop="logoUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.logoUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="联系邮箱" align="center" prop="email" />
      <el-table-column label="商户状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ statusMap[scope.row.status] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="营业模式" align="center" prop="businessPattern">
        <template #default="scope">
          {{ businessPatternMap[scope.row.businessPattern] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewDetail(scope.row)">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['core:storeInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['core:storeInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户基本信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="storeInfoRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入商户编码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择商户类型" style="width: 100%">
                <el-option v-for="(label, value) in typeMap" :key="value" :label="label" :value="parseInt(value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择商户状态" style="width: 100%">
                <el-option v-for="(label, value) in statusMap" :key="value" :label="label" :value="parseInt(value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商户LOGO" prop="logoUrl">
          <image-upload v-model="form.logoUrl"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入联系邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业模式" prop="businessPattern">
              <el-select v-model="form.businessPattern" placeholder="请选择营业模式" style="width: 100%">
                <el-option v-for="(label, value) in businessPatternMap" :key="value" :label="label" :value="parseInt(value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="逻辑删除标志" prop="delFlag" v-if="false">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标志" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商户详情弹窗 - 从右向左滑动 -->
    <el-drawer
      v-model="detailDrawer"
      title="商户详细信息"
      direction="rtl"
      size="600px"
      :before-close="handleDetailClose"
    >
      <div class="detail-container" v-loading="detailLoading">
        <div v-if="storeDetailData">
          <!-- 基本信息 -->
          <el-card class="detail-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">基本信息</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="商户名称">{{ storeDetailData.storeInfo?.name }}</el-descriptions-item>
              <el-descriptions-item label="商户编码">{{ storeDetailData.storeInfo?.code }}</el-descriptions-item>
              <el-descriptions-item label="商户类型">{{ typeMap[storeDetailData.storeInfo?.type] }}</el-descriptions-item>
              <el-descriptions-item label="商户状态">
                <el-tag :type="storeDetailData.storeInfo?.status === 1 ? 'success' : 'danger'">
                  {{ statusMap[storeDetailData.storeInfo?.status] }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="联系人">{{ storeDetailData.storeInfo?.contactName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ storeDetailData.storeInfo?.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="联系邮箱">{{ storeDetailData.storeInfo?.email }}</el-descriptions-item>
              <el-descriptions-item label="营业模式">{{ businessPatternMap[storeDetailData.storeInfo?.businessPattern] }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="logo-section" v-if="storeDetailData.storeInfo?.logoUrl">
              <div class="section-title">商户LOGO</div>
              <image-preview :src="storeDetailData.storeInfo.logoUrl" :width="120" :height="120"/>
            </div>
          </el-card>

          <!-- 地址信息 -->
          <el-card class="detail-card" shadow="never" v-if="storeDetailData.storeDetail">
            <template #header>
              <div class="card-header">
                <span class="card-title">地址信息</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="省份">{{ storeDetailData.storeDetail.province }}</el-descriptions-item>
              <el-descriptions-item label="城市">{{ storeDetailData.storeDetail.city }}</el-descriptions-item>
              <el-descriptions-item label="区县">{{ storeDetailData.storeDetail.district }}</el-descriptions-item>
              <el-descriptions-item label="详细地址">{{ storeDetailData.storeDetail.address }}</el-descriptions-item>
              <el-descriptions-item label="经度">{{ storeDetailData.storeDetail.longitude }}</el-descriptions-item>
              <el-descriptions-item label="纬度">{{ storeDetailData.storeDetail.latitude }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ storeDetailData.storeDetail.phone }}</el-descriptions-item>
              <el-descriptions-item label="营业状态">
                <el-tag :type="storeDetailData.storeDetail.status === 1 ? 'success' : 'danger'">
                  {{ storeDetailData.storeDetail.status === 1 ? '营业中' : '已关闭' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="资质信息" :span="2">{{ storeDetailData.storeDetail.qualificationInfo }}</el-descriptions-item>
              <el-descriptions-item label="商户描述" :span="2">{{ storeDetailData.storeDetail.description }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="license-section" v-if="storeDetailData.storeDetail.businessLicenseUrl">
              <div class="section-title">营业执照</div>
              <image-preview :src="storeDetailData.storeDetail.businessLicenseUrl" :width="200" :height="150"/>
            </div>
          </el-card>

          <!-- 营业时间 -->
          <el-card class="detail-card" shadow="never" v-if="storeDetailData.businessTimes && storeDetailData.businessTimes.length > 0">
            <template #header>
              <div class="card-header">
                <span class="card-title">营业时间</span>
              </div>
            </template>
            <el-table :data="storeDetailData.businessTimes" border stripe>
              <el-table-column label="星期" align="center" width="100">
                <template #default="scope">
                  {{ dayOfWeekMap[scope.row.dayOfWeek] }}
                </template>
              </el-table-column>
              <el-table-column label="开始时间" align="center" width="120">
                <template #default="scope">
                  {{ formatTime(scope.row.openTime) }}
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="120">
                <template #default="scope">
                  {{ formatTime(scope.row.closeTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
        
        <div v-else-if="!detailLoading" class="no-data">
          <el-empty description="暂无详细信息" />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="StoreInfo">
import { listStoreInfo, getStoreInfo, delStoreInfo, addStoreInfo, updateStoreInfo ,getStoreFullInfo } from "@/api/core/storeInfo"
import { ref, reactive, toRefs, getCurrentInstance, computed } from 'vue'

const { proxy } = getCurrentInstance()

// 数据映射字典
const typeMap = { 1: '连锁超市', 2: '便利店', 3: '个体户' }
const statusMap = { 0: '禁用', 1: '启用' }
const businessPatternMap = { 
  1: '统一时间模式', 
  2: '周末延长模式', 
  3: '周末高峰模式', 
  4: '24小时营业模式' 
}

// 星期几映射字典
const dayOfWeekMap = {
  1: '星期一',
  2: '星期二', 
  3: '星期三',
  4: '星期四',
  5: '星期五',
  6: '星期六',
  7: '星期日'
}

const storeInfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 详情弹窗相关变量
const detailDrawer = ref(false)
const detailLoading = ref(false)
const storeDetailData = ref(null)

// 格式化时间显示（从ISO时间字符串中提取时分秒）
function formatTime(timeString) {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const seconds = date.getSeconds().toString().padStart(2, '0')
    return `${hours}:${minutes}:${seconds}`
  } catch (error) {
    return timeString
  }
}

// 计算启用和禁用的商户数量
const enabledCount = computed(() => {
  return storeInfoList.value.filter(item => item.status === 1).length
})

const disabledCount = computed(() => {
  return storeInfoList.value.filter(item => item.status === 0).length
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    code: null,
    type: null,
    logoUrl: null,
    contactName: null,
    contactPhone: null,
    email: null,
    status: null,
    businessPattern: null
  },
  rules: {
    name: [
      { required: true, message: "商户名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "商户编码不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "请选择商户类型", trigger: "change" }
    ],
    contactName: [
      { required: true, message: "联系人姓名不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号", trigger: "blur" }
    ],
    email: [
      { required: true, message: "联系邮箱不能为空", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
    ],
    status: [
      { required: true, message: "请选择商户状态", trigger: "change" }
    ],
    businessPattern: [
      { required: true, message: "请选择营业模式", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 状态筛选功能
function filterByStatus(status) {
  queryParams.value.status = status
  queryParams.value.pageNum = 1
  getList()
}

// 查看详情功能
function handleViewDetail(row) {
  detailDrawer.value = true
  detailLoading.value = true
  storeDetailData.value = null
  
  // 调用后端接口获取详细信息
  getStoreFullInfo(row.id).then(response => {
    storeDetailData.value = response.data
    detailLoading.value = false
  }).catch(error => {
    console.error('获取商户详情失败:', error)
    proxy.$modal.msgError('获取商户详情失败')
    detailLoading.value = false
  })
}

// 关闭详情弹窗
function handleDetailClose() {
  detailDrawer.value = false
  storeDetailData.value = null
}
/** 查询商户基本信息列表 */
function getList() {
  loading.value = true
  listStoreInfo(queryParams.value).then(response => {
    storeInfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    code: null,
    type: 1,
    logoUrl: null,
    contactName: null,
    contactPhone: null,
    email: null,
    status: 1,
    delFlag: null,
    createTime: null,
    updateTime: null,
    businessPattern: 1
  }
  proxy.resetForm("storeInfoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.status = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商户基本信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStoreInfo(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商户基本信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStoreInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStoreInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商户基本信息编号为"' + _ids + '"的数据项？').then(function() {
    return delStoreInfo(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('core/storeInfo/export', {
    ...queryParams.value
  }, `storeInfo_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.status-filter {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mr-2 {
  margin-right: 8px;
}

/* 详情弹窗样式 */
.detail-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin: 16px 0 8px 0;
}

.logo-section,
.license-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.no-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

/* 描述列表样式优化 */
:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

/* 表格样式优化 */
:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  color: #303133;
}

/* 标签样式 */
:deep(.el-tag) {
  font-weight: 500;
}

/* 图片预览样式 */
:deep(.image-preview) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
</style>
